<?php 
/**
* 验证码类
*/
class Code
{
	//配置
	public $config = array(
		'width'=>200,
		'height'=>80,
		'lenght'=>4,
		'linenum'=>0,
		'diannum'=>0,
		'disturb'=>false,
		'fontsize'=>20,
		'str'=>'qwertyuiopasdfghjklzxcvm1234567890QWERTYUIOPASDFGHJKLZXCVBNMN'
	);
	//画布
	public $src;

	//构造函数，初始化
	public function __construct($config=array())
	{
		$this->config = array_merge($this->config,$config);
		$this->getfontssize();
	}
	//
	//动态计算字体大小
	public function getfontssize()
	{
		$height = $this->height*0.7;
		$width = ($this->width/$this->lenght)*0.7;

		$this->fontsize = $height>$width ? $width :$height; 

	}
	//生成验证码
	public function entry()
	{
		$this->createImg();
		// 创建画布
		// 画线
		$this->addLine();
		// 画点
		$this->addDian();

		$this->adddisturb();
		// 画字
		$this->addFonts();
		// 输出
		$this->outImg();
	}
	//魔术方法获取属性
	public function __get($name)
	{
		return $this->config[$name];
	}
	//魔术方法设置属性
	public function __set($name,$value)
	{
		$this->config[$name] = $value;
	}
	//加干扰字
	public function adddisturb()
	{
		if($this->disturb){
			for ($i=0; $i < 20; $i++) {
				$word = $this->str[mt_rand(0,strlen($this->str)-1)];

				$color = imageColorAllocate($this->src,mt_rand(50,255),mt_rand(50,255),mt_rand(50,255));

				imagettftext ( $this->src , $this->fontsize/3,mt_rand(-15,15) , mt_rand(0,$this->width) , mt_rand(0,$this->height), $color , './CharlemagneStd-Bold.otf' , $word);
			}
		}
	}
	//加线
	public function addLine()
	{
		for ($i=0; $i <$this->linenum ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
			imageline ( $this->src , mt_rand(0,$this->width) , mt_rand(0,$this->height) , mt_rand(0,$this->width)  , mt_rand(0,$this->height), $color );
		}
	}
	//加点
	public function addDian()
	{
		for ($i=0; $i <$this->diannum ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
			imagesetpixel ( $this->src , mt_rand(0,$this->width) , mt_rand(0,$this->height), $color );
		}
	}
	//创建画布
	public function createImg()
	{
		//创建画布
		$this->src = imageCreateTrueColor($this->width,$this->height); 
		// 选颜色
		$color = imageColorAllocate($this->src,200,200,200); 

		// //填充
		imageFill($this->src,0,0,$color);
	}
	//加字
	public function addFonts()
	{
		for ($i=0; $i < $this->lenght; $i++) { 


			$word = $this->str[mt_rand(0,strlen($this->str)-1)];

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));

			$diff = $this->width/$this->lenght;

			$width = ($diff-$this->fontsize)/2+$diff*$i;

			imagettftext ( $this->src , $this->fontsize,mt_rand(-15,15) , $width , ($this->height+$this->fontsize)/2 , $color , './CharlemagneStd-Bold.otf' , $word);
		}

	}
	//输出图像
	public function outImg()
	{
		// 发头部
		header("Content-type: image/png");
		// 输出图片
		imagepng($this->src);  


		imageDestroy($this->src);
	}

}

















 ?>